package com.ssplayer.service;

import java.io.IOException;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.animation.AnimationUtils;

import com.ssplayer.activity.MusicPlayerActivity;
import com.ssplayer.activity.R;
import com.ssplayer.application.MyApplication;
import com.ssplayer.bean.Lyric;
import com.ssplayer.bean.Music;
import com.ssplayer.bean.MusicAction;
import com.ssplayer.bean.MusicMsg;
import com.ssplayer.custom.LrcProcess;
import com.ssplayer.utils.MediaUtils;

public class MusicService extends Service implements OnCompletionListener {

	private static final int UPDATE_PROGRESS = 1;
	private static final int STOP_PROGRESS = 2;

	private MyApplication myApp;
	private SharedPreferences sharedPreferences;
	private MediaPlayer mediaPlayer;
	private List<Music> musics;
	private int currentMusic;
	private int currentTime;
	private int duration;
	private LrcProcess lrcProcess;
	private List<Lyric> lyrics;
	private int index;// 歌词检索值

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {

		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UPDATE_PROGRESS:
				if (mediaPlayer != null) {
					currentTime = mediaPlayer.getCurrentPosition();
					Intent intent = new Intent();
					intent.setAction(MusicAction.MUSIC_CURRENT);
					intent.putExtra("currentTime", currentTime);
					sendBroadcast(intent);
					handler.sendEmptyMessageDelayed(UPDATE_PROGRESS, 1000);
				}
				break;
			case STOP_PROGRESS:
				Intent intent = new Intent();
				intent.setAction(MusicAction.MUSIC_CURRENT);
				intent.putExtra("currentTime", 0);
				sendBroadcast(intent);
				handler.removeMessages(UPDATE_PROGRESS);
				break;
			}
		};
	};

	@Override
	public void onCreate() {
		super.onCreate();
		TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		telephonyManager.listen(new MyPhoneStateListener(),
				PhoneStateListener.LISTEN_CALL_STATE);
		myApp = (MyApplication) getApplication();
		sharedPreferences = getSharedPreferences("musicStore",
				Context.MODE_PRIVATE);
		musics = MediaUtils.getMusics(getApplicationContext(),
				myApp.getCurrentlist());
		// 只需创建一次媒体播放器
		mediaPlayer = new MediaPlayer();
		mediaPlayer.setOnCompletionListener(this);
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		int msg = intent.getIntExtra("msg", 0);
		if (msg == MusicMsg.PLAY_FROM_FILE) {
			String path = intent.getStringExtra("path");
			try {
				mediaPlayer.reset();// 把各项参数恢复到初始状态,否则只能播放一首
				mediaPlayer.setDataSource(path);
				mediaPlayer.prepare();
				mediaPlayer.start();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			currentMusic = intent.getIntExtra("currentMusic", 0);
			// 再次初始化歌词出现异常
			// initLyric();
			switch (msg) {
			case MusicMsg.PLAY_MSG:
				play(0);
				break;
			case MusicMsg.PROGRESS_CHANGE:
				currentTime = intent.getIntExtra("currentTime", 0);
				play(currentTime);
				break;
			case MusicMsg.PAUSE_MSG:
				pause();
				break;
			case MusicMsg.CONTINUE_MSG:
				musicontinue();
				break;
			case MusicMsg.PREVIOUS_MSG:
				previous();
				break;
			case MusicMsg.NEXT_MSG:
				next();
				break;
			case MusicMsg.STOP_MSG:
				stop();
				break;
			case MusicMsg.SHOWLRC_MSG:
				// 根据当前音乐显示歌词，虽然没有播放，也要获取当前音乐，来自MusicPlayerActivity
				initLyric();
				break;
			}
		}
		return super.onStartCommand(intent, flags, startId);
	}

	private void play(int currentTime) {

		try {
			mediaPlayer.reset();// 把各项参数恢复到初始状态,否则只能播放一首
			mediaPlayer.setDataSource(musics.get(currentMusic).getUrl());
			mediaPlayer.prepare();
			mediaPlayer
					.setOnPreparedListener(new PreparedListener(currentTime));
			handler.sendEmptyMessage(UPDATE_PROGRESS);
			setPlayStatus(MusicMsg.STATUS_PLAYING);
			initLyric();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void pause() {
		mediaPlayer.pause();
		setPlayStatus(MusicMsg.STATUS_PAUSE);
	}

	/**
	 * 继续播放
	 */
	private void musicontinue() {
		mediaPlayer.start();
		setPlayStatus(MusicMsg.STATUS_PLAYING);
	}

	private void previous() {
		currentMusic--;
		if (currentMusic == -1) {
			currentMusic = musics.size() - 1;
		}
		musicChangeBroadcast(currentMusic);
		play(0);

	}

	private void next() {
		currentMusic++;
		if (currentMusic == musics.size()) {
			currentMusic = 0;
		}
		musicChangeBroadcast(currentMusic);
		play(0);
	}

	/**
	 * 停止
	 */
	private void stop() {
		mediaPlayer.stop();
		handler.sendEmptyMessage(STOP_PROGRESS);
		setPlayStatus(MusicMsg.STATUS_STOP);
	}

	/**
	 * 改变音乐播放状态并发送广播
	 * 
	 * @param play_status
	 */
	private void setPlayStatus(int play_status) {
		myApp.setMplay_status(play_status);
		Intent intent = new Intent();
		intent.setAction(MusicAction.CONTROL_ACTION);
		sendBroadcast(intent);
	}

	/**
	 * 切换歌曲时通知界面更新
	 */
	private void musicChangeBroadcast(int currentMusic) {
		Intent intent = new Intent();
		intent.putExtra("currentMusic", currentMusic);
		intent.setAction(MusicAction.UPDATE_ACTION);
		sendBroadcast(intent);
	}

	/**
	 * 
	 * 实现一个OnPrepareLister接口,当音乐准备好的时候开始播放
	 * 
	 */
	private final class PreparedListener implements OnPreparedListener {
		private int currentTime;

		public PreparedListener(int currentTime) {
			this.currentTime = currentTime;
		}

		@Override
		public void onPrepared(MediaPlayer mp) {
			mediaPlayer.start(); // 开始播放
			if (currentTime > 0) { // 如果音乐不是从头播放
				mediaPlayer.seekTo(currentTime);
			}
		}
	}

	/**
	 * 播放完成时的监听器
	 */
	@Override
	public void onCompletion(MediaPlayer mp) {
		// 判断当前是否有音乐在播放，如果播放时间大于0则有，进入下一曲，如果没有则停止播放
		// 此处是为解决直接启动服务（打开音乐主界面）时，会跳过当前音乐播放下一首的问题
		if (currentTime > 0) {
			switch (sharedPreferences.getInt("play_mode", MusicMsg.MODE_ORDER)) {
			case MusicMsg.MODE_ORDER:
				next();
				break;
			case MusicMsg.MODE_SHUFFLE:
				currentMusic = getRandomIndex();
				play(0);
				break;
			case MusicMsg.MODE_REPEAT_ONCE:
				play(0);
				break;
			}
			musicChangeBroadcast(currentMusic);
		} else {
			stop();
		}
	}

	private int getRandomIndex() {
		int index = (int) (Math.random() * musics.size());
		return index;
	}

	/**
	 * 来电监听
	 */

	private class MyPhoneStateListener extends PhoneStateListener {

		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			switch (state) {
			case TelephonyManager.CALL_STATE_IDLE:// 挂机状态
				musicontinue();
				break;
			case TelephonyManager.CALL_STATE_RINGING:// 响铃状态
			case TelephonyManager.CALL_STATE_OFFHOOK:// 接听状态
				pause();
				break;
			}
		}
	}

	/**
	 * 退出时保存正在播放的音乐
	 */
	private void savePlayingMusic() {
		setPlayStatus(MusicMsg.STATUS_STOP);
		handler.sendEmptyMessage(STOP_PROGRESS);
		Editor editor = sharedPreferences.edit();
		editor.putInt("currentMusic", currentMusic);
		editor.commit();
	}

	// ************************以下为歌词部分**************************************
	/**
	 * 初始化歌词配置
	 */
	public void initLyric() {
		lrcProcess = new LrcProcess();
		// 读取歌词文件
		lrcProcess.readLyric(musics.get(currentMusic).getUrl());
		// 传回处理后的歌词文件
		lyrics = lrcProcess.getLyrics();
		MusicPlayerActivity.lrcView.setLyrics(lyrics);
		// 切换带动画显示歌词
		MusicPlayerActivity.lrcView.setAnimation(AnimationUtils.loadAnimation(
				MusicService.this, R.anim.alpha_z));
		handler.post(mRunnable);
	}

	Runnable mRunnable = new Runnable() {

		@Override
		public void run() {
			MusicPlayerActivity.lrcView.setIndex(lrcIndex());
			MusicPlayerActivity.lrcView.invalidate();
			handler.postDelayed(mRunnable, 100);
		}
	};

	/**
	 * 根据时间获取歌词显示的索引值
	 * 
	 * @return
	 */
	public int lrcIndex() {
		if (mediaPlayer.isPlaying()) {
			currentTime = mediaPlayer.getCurrentPosition();
			duration = mediaPlayer.getDuration();
		}
		if (currentTime < duration) {
			for (int i = 0; i < lyrics.size(); i++) {
				if (i < lyrics.size() - 1) {
					if (currentTime < lyrics.get(i).getLyricTime() && i == 0) {
						index = i;
					}
					if (currentTime > lyrics.get(i).getLyricTime()
							&& currentTime < lyrics.get(i + 1).getLyricTime()) {
						index = i;
					}
				}
				if (i == lyrics.size() - 1
						&& currentTime > lyrics.get(i).getLyricTime()) {
					index = i;
				}
			}
		}
		return index;
	}

	@Override
	public void onDestroy() {
		// 保存正在播放的音乐
		savePlayingMusic();
		mediaPlayer.stop();
		mediaPlayer.release();
		mediaPlayer = null;
		handler.removeCallbacks(mRunnable);
		handler.removeMessages(UPDATE_PROGRESS);
	}
}
